<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="hdCheck(todo.id)" />
      <span v-show="!todo.isEdit">{{ todo.title }}</span>
      <input
        type="text"
        @blur="hdBlur(todo, $event)"
        v-show="todo.isEdit"
        :value="todo.title"
        ref="inputTitle"
      />
    </label>
    <button class="btn btn-danger" @click="hdDelete(todo.id)">删除</button>
    <button class="btn btn-edit" v-show="!todo.isEdit" @click="hdEdit(todo)">
      编辑
    </button>
  </li>
</template>
<script>
import pubsub from "pubsub-js";
export default {
  name: "NoteItem",
  props: ["todo"],
  methods: {
    hdCheck(id) {
      //取反done值
      // this.checkTodo(id);
      this.$bus.$emit("checkTodo", id);
    },
    hdDelete(id) {
      if (confirm("确定删除吗？")) {
        // this.delTodo(id);//函数名
        // this.$bus.$emit("delTodo", id);//自定义事件名
        pubsub.publish("delTodo", id); //消息名
      }
    },
    hdEdit(todo) {
      /* if (todo.hasOwnProperty("isEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      } */
      if (Object.prototype.hasOwnProperty.call(todo, "isEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      }
      this.$nextTick(function () {
        this.$refs.inputTitle.focus();
      });
    },
    hdBlur(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return;
      this.$bus.$emit("updateTodo", todo.id, e.target.value);
    },
  },
};
</script>

<style>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li .btn {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover {
  background-color: #ddd;
}
li:hover .btn {
  display: block;
}
</style>